<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/8/9
 * Time: 13:59
 */

namespace app\web\controller;

use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\Recode;
use app\common\model\WechatRecode;
use \think\Cache;
use \think\Controller;
use \app\common\lib\Jssdk;
use \think\Env;
use app\common\model\Authenticate;
use app\common\lib\Aes;
use app\common\lib\IAuth;

/**
 * 鉴爱H5页面
 * Class IdentifyLove
 * @package app\web\controller
 */
class IdentifyLove extends Controller
{
    //微信分享图片
    protected $share_img = '';

    public function _initialize()
    {
        $this->share_img = Env::get('host.photo') . '/test/authenticate_love/share_logo.jpg';


    }

    /**
     * 鉴爱说明
     * @return mixed
     */
    public function explain()
    {
        return $this->fetch('explain', ['img_host' => Env::get('host.photo')]);
    }

    /**
     * 鉴爱H5 填写信息页面
     * @return bool|mixed|\think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function add()
    {
        //由于微信分享域名被封禁了，所以鉴爱暂时跳转到官网
        return $this->redirect('https://www.goddessxzns.com');

        // rid=553540
        $token_param = input('token', '');
        $isEncode = input('is_encode/d', 0);
        if (!$isEncode)
        {
            $token = urldecode($token_param);
            //把空格替换成“+”
            $token = str_replace(' ', '+', $token);
        } elseif ($isEncode === 2)
        {
            $token = base64_decode($token_param, true);
        } else
        {
            $token = $token_param;
        }
        // access-token AES解密
        $str = (new Aes())->decryptWithOpenssl($token);
        if (empty($str))
        {
            return show(config('code.error'), '参数错误');
        }

        parse_str($str, $arr);

        if (!is_array($arr) || !isset($arr['rid']))
        {
            return show(config('code.error'), '参数错误');
        }
        $rid = $arr['rid'];
        if (empty($rid))
        {
//            return show(config('code.error'), $rid . 'rid不能为空！');
            return show(config('code.error'), '参数错误');
        }

        $recode = (new Recode())->getRecode(['id' => $rid]);//通过rid 获取档案信息
        if (empty($recode))//档案信息获取失败，返回错误页面
        {
//            return show(config('code.error'), $rid . '档案获取失败！');
            return show(config('code.error'), '档案获取失败');
        }
        //检查session，如果不存在，那么就直接跳转到登录
        $this->checkLogin($token_param, $isEncode);
        //-------test-------
//        session('love.unionid', 'mark');
//        session('love.name', 'mark');
//        session('love.headimgurl', 'http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eowXRHyNwUiaJFUOITfuicI2VOwVmJqQgWia11Cc8wQBoRJYpkMrJkoF7swqAPwQCcVCWW62o8YwGDCA/132');
//        session('love.sex', '1');
        //-------test-------
        //根据unionid查询这个用户的档案和性别信息，传到页面里
//        $data = (new WechatRecode())->getWechatRecodeWithUnionid(['uid' => $recode['uid'], 'unionid' => session('love.unionid')]);
        $data = (new WechatRecode())->getWechatRecodeByUnionid(['unionid' => session('love.unionid')]);
        $sex = session('love.sex');
        if ($data !== false && !empty($data))
        {
            if (isset($data['birth_time']) && $data['birth_time'] != '')
            {
                $data['birth_time_input'] = $data['birth_time'];
            }
            if (isset($data['sex']) && $data['sex'])
            {
                $sex = $data['sex'];
            }
            if (isset($data['type']) && $data['type'])
            {
                $sex = $data['type'];
            }
        } else
        {//设置初始的时间
            $data['birth_time'] = '1995-01-01 00:00';
            $data['birth_time_input'] = '';
            $data['birth_place'] = '';
            $data['longitude'] = '';
            $data['latitude'] = '';
        }

        //session不为空，那么跳转到下面的页面
        $signPackage = (new Jssdk())->getSignPackage();
        $data = [
            'user' => $data,
            'rid' => $rid,//用户档案
            'uid' => $recode['uid'],//用户id
            'icon_url' => session('love.headimgurl') ?: Env::get('host.photo') . '/avatar_default_2.png',//微信登录的头像
            'name' => session('love.name'),//微信登录的名字
            'sex' => $sex
        ];

        $time = time();
        // 情人节改标题
        if ($time >= strtotime('2019-02-14 00:00:00'))
        {
            $share_title = '【准了APP】浪漫情人节，你敢来鉴定我们潜在的情人关系吗？';
        } else
        {
            $share_title = '【准了APP】你敢来鉴定我们潜在的情人关系吗？';// 情人节将至，
        }

        return $this->fetch('add', [
            'title' => '「' . $recode['name'] . '」邀请你鉴爱',//网页标题
            'share_title' => $share_title,//微信分享标题
            'share_introduction' => '假如我们在一起，能碰撞出怎样的火花，会产生怎样的爱情？',//微信分享内容
            'share_img' => $this->share_img,
            'signPackage' => $signPackage,//微信签名
            'data' => $data//带过去的数据
        ]);

    }

    /**
     * 鉴爱 个人信息填写完成，查看结果
     * @return \think\response\Json
     * @throws ApiException
     */
    public function save()
    {
        $data = request()->param();

        $validate = validate('Recode');

        if (!$validate->scene('wechat_add')->check($data))
        {
            return show(config('code.error'), (string)$validate->getError());
        }
        $data['birth_place'] = trim($data['birth_place']);

        //获取日月升信息
        $time = strtotime($data['birth_time']);
        $year = date('Y', $time);
        $month = date('m', $time);
        $day = date('d', $time);
        $hour = date('H', $time);
        $minute = date('i', $time);

        $data['sun_moon_asc'] = $this->getSunMoonAsc($year, $month, $day, $hour, $minute, $data['longitude'], $data['latitude']);

        $nowTime = time();

        $data['create_time'] = $nowTime;
        $data['update_time'] = $nowTime;
        $data['unionid'] = session('love.unionid');
        $rid = $data['rid'];
        unset($data['rid']);

        try
        {
            $wid = (new WechatRecode())->insertWechatRecode($data);
            Cache::rm('wechat_recode_lists_' . $data['uid']);
        }
        catch (\Exception $e)
        {
            \think\Log::write($e->getMessage(), 'error', true);
            throw new ApiException('计算失败，请稍候再试');
        }
        // 跳转到计算结果页面
        $token = [
            'uid' => $data['uid'],
            'rid1' => $rid,
            'wid2' => $wid,
            'is_save' => 1,
        ];
        // 生成加密数据
        $token = IAuth::setSign($token);

        return show(config('code.success'), '加载成功', '/web/identify_love/detail?token=' . $token);
    }

    /**
     * 查看鉴爱结果
     * @return bool|mixed
     * @throws ApiException
     */
    public function detail()
    {
        $token = input('token', '');
        $isEncode = input('is_encode/d', 0);
        if (!$isEncode)
        {
            //注意token中不能存在空格，因为php的urldecode方法会把“+”替换成空格
            $token = urldecode($token);
            //把空格替换成“+”
            $token = str_replace(' ', '+', $token);
        } elseif ($isEncode === 2)
        {
            $token = base64_decode($token, true);
        }
        // access-token AES解密
        $str = (new Aes())->decryptWithOpenssl($token);

        if (empty($str))
        {
            return "<h1>加载失败,请稍后重试！</h1>";
        }
        parse_str($str, $arr);

        if (!is_array($arr))
        {
            return "<h1>加载失败,请稍后重试！</h1>";
        }
        $rid1 = isset($arr['rid1']) ? (int)($arr['rid1']) : 0;
        $rid2 = isset($arr['rid2']) ? (int)($arr['rid2']) : 0;
        $wid1 = isset($arr['wid1']) ? (int)($arr['wid1']) : 0;
        $wid2 = isset($arr['wid2']) ? (int)($arr['wid2']) : 0;
        $is_save = isset($arr['is_save']) ? (int)($arr['is_save']) : 0;
        $uid = $arr['uid'];

        //验证参数是否正确
        if ((!$rid1 && !$wid1) || ($rid1 && $wid1) || (!$rid2 && !$wid2) || ($rid2 && $wid2))
        {
            return "<h1>加载失败,请稍后重试！</h1>";
        }

        $map = [
            'atype' => 1,
            'uid' => $uid,
            'rid1' => $rid1,
            'wid1' => $wid1,
            'rid2' => $rid2,
            'wid2' => $wid2,
            'is_save' => $is_save
        ];

        $data = (new Authenticate())->getAuthenticateResult($map);

        //注意h5里面不能切换，所以只显示一种结果
        if (!empty($data) && isset($data['result_list1']) && isset($data['result_list2']))
        {
            if ($is_save === 1)
            {
                $arr['result_list1'] = $data['result_list2'];
            } else
            {
                $arr['result_list1'] = $data['result_list1'];
            }
        } else
        {
            $arr = [];
        }

        //设置圆环的颜色
        $colors = ['#ffcee0', '#87e5f1', '#a3b6ff', '#e8beff'];
        foreach ($arr['result_list1'] as $k => $v)
        {
            if ($k == 0)
                continue;
            else
                $arr['result_list1'][$k]['color'] = $colors[$k - 1];
        }

        //获取两个档案信息
        if ($rid1)
        {
            $recode1 = $this->getCustomDataWithRid($uid, $rid1);
        } else
        {
            $recode1 = $this->getCustomDataWithWidAndUid($wid1, $uid);
        }
        if ($rid2)
        {
            $recode2 = $this->getCustomDataWithRid($uid, $rid2);
        } else
        {
            $recode2 = $this->getCustomDataWithWidAndUid($wid2, $uid);
        }

        $arr['recodes'] = [$recode1, $recode2];

        //是否为刚填写完信息之后的查看详情,是=>交换档案信息，以自己为主
        if ($is_save === 1)
        {
            $temp = $arr['recodes'][0];
            $arr['recodes'][0] = $arr['recodes'][1];
            $arr['recodes'][1] = $temp;
        }

        //获取微信签名，用于二次分享
        $signPackage = (new Jssdk())->getSignPackage();
        //返回数据
        return $this->fetch('detail', [
            'title' => '鉴定结果',
            'share_title' => '【准了APP】真爱经得起鉴定，「' . $arr['recodes'][1]['name'] . '」对「' . $arr['recodes'][0]['name'] . '」的感情竟是这样的？',
            'share_introduction' => '这是我们的秘密，谁都不许看！',
            'share_img' => $this->share_img,
            'signPackage' => $signPackage,
            'data' => $arr,
        ]);
    }


    /**
     * 微信登陆
     */
    public function weixin_login()
    {
        $token = trim(input('get.token'));
        $isEncode = input('is_encode/d', 0);
        $appid = config('wechat.mp_appid');
        $domain = Env::get('host.domain');
        $redirect_uri = urlencode($domain . '/web/identify_love/weixin_back' . '/is_encode/' . $isEncode);
        header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . $token . '#wechat_redirect');

        exit;
    }

    /**
     * 微信登陆返回
     */
    public function weixin_back()
    {
        $appid = config('wechat.mp_appid');
        $appsecret = config('wechat.mp_secret');
        $isEncode = input('is_encode/d', 0);

        $code = input('get.code');
        if (empty($code)) $this->error('微信授权失败！');

        $token = input('get.state');
        if (empty($token)) $this->error('获取token失败！');
        if (empty(session('love.access_token')))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
            $access_token = json_decode(file_get_contents($access_token_url));
            if (isset($access_token->errcode))
            {
                $this->error('授权失败');
            }
            session('love.access_token', $access_token->access_token);
            session('love.refresh_token', $access_token->refresh_token);
            session('love.openid', $access_token->openid);
        }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . session('love.access_token') . '&openid=' . session('love.openid') . '&lang=zh_CN';
        $user_info = json_decode(file_get_contents($user_info_url));
        if (isset($user_info->errcode))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . session('love.refresh_token');
            $access_token = json_decode(file_get_contents($access_token_url), true);
            if (!empty($access_token) && isset($access_token['access_token']) && isset($access_token['refresh_token']) && isset($access_token['openid']))
            {
                session('love.access_token', $access_token['access_token']);
                session('love.refresh_token', $access_token['refresh_token']);
                session('love.openid', $access_token['openid']);

                $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token['access_token'] . '&openid=' . $access_token['openid'] . '&lang=zh_CN';
                $user_info = json_decode(file_get_contents($user_info_url));
                if (isset($user_info->errcode))
                {
                    echo '<h1>错误：</h1>' . $user_info->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
                    exit;
                }
            } else
            {//失败的话，重新授权登录
                $this->redirect('/web/identify_love/weixin_login?token=' . urlencode($token) . '&is_encode=' . $isEncode);
            }
        }
        //把unionid、headimgurl、name 保存到session里
        session('love.unionid', $user_info->unionid);
        session('love.headimgurl', $user_info->headimgurl);
        session('love.name', $user_info->nickname);
        session('love.sex', $user_info->sex);

        $this->redirect('/web/identify_love/add?token=' . urlencode($token) . '&is_encode=' . $isEncode);
    }


    /**
     * 检查session里是否有  unionid、headimgurl、name 这三个参数，如果为空，那么跳转到微信登录页面
     * @param $token
     * @param $isEncode
     */
    private function checkLogin($token, $isEncode)
    {
        if (empty(session('love.unionid')))
        {
            $this->redirect('/web/identify_love/weixin_login?token=' . urlencode($token) . '&is_encode=' . $isEncode);
        }
    }

    /**
     * 根据出生时间和地点经纬度以及时区获取用户 日月生 信息
     * @param $year
     * @param $month
     * @param $day
     * @param $hour
     * @param $minute
     * @param $longitude
     * @param $latitude
     * @param int $timezone
     * @param bool $is_get_sign 是否获取星座（星座返回数字）
     * @return string
     */
    private function getSunMoonAsc($year, $month, $day, $hour, $minute, $longitude, $latitude, $timezone = 8, $is_get_sign = false)
    {
        // 查询当前星盘日月水金火木土等星落座落宫存入数据库
        $astro_data = getTheRecodeAstro($year, $month, $day, $hour, $minute, $longitude, $latitude, $timezone);
        $sign_names = config('astrolog.sign_name');

        $sun = explode("-", $astro_data['sun'])[0];
        $moon = explode("-", $astro_data['moon'])[0];
        $asc = explode("-", $astro_data['asc'])[0];
        $sun_moon_asc = '日' . explode("|", $sign_names[$sun])[2] . '月' . explode("|", $sign_names[$moon])[2] . '升' . explode("|", $sign_names[$asc])[2];

        $result = $sun_moon_asc;

        if ($is_get_sign)
        {
            $result = ['sun_moon_asc' => $sun_moon_asc, 'sign' => (int)($sun)];
        }
        return $result;
    }

    /**
     * 根据 rid 获取自定义的数据，用于传给前端（注意：type=0，rid有效）
     * @param $rid
     * @return mixed
     * @throws \app\common\lib\exception\ApiException
     */
    private function getCustomDataWithRid($uid, $rid)
    {
        $recode = (new Recode())->getRecode(['uid' => $uid, 'id' => $rid]);//通过rid 获取档案信息
        $recode1['type'] = 0;
        $recode1['id'] = $recode['id'];
        $recode1['uid'] = $recode['uid'];
        $recode1['name'] = $recode['name'];
        $map = $this->getSunMoonAsc($recode['year'], $recode['month'], $recode['day'], $recode['hour'], $recode['minute'], ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'], ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'], 8, true);
        $recode1['sun_moon_asc'] = $map['sun_moon_asc'];
        $recode1['avatar'] = $recode['avatar'] != '' ? Util::getImgUrl($recode['avatar']) : Env::get('host.domain') . '/static/identify_love/img/c_' . $map['sign'] . '.png';

        return $recode1;
    }

    /**
     * 根据uid和wid 获取自定义格式的数据，用于传给前端（注意：type=1，wid有效）
     * @param $wid
     * @param $uid
     * @return mixed
     * @throws ApiException
     */
    private function getCustomDataWithWidAndUid($wid, $uid)
    {
        $wechat_recode = (new WechatRecode())->getWechatRecode(['wid' => $wid, 'uid' => $uid]);
        $recode1['type'] = 1;
        $recode1['id'] = $wid;
        $recode1['uid'] = $uid;
        $recode1['name'] = $wechat_recode['name'];
        $recode1['avatar'] = $wechat_recode['avatar'] != '' ? $wechat_recode['avatar'] : Env::get('host.domain') . '/static/identify_love/img/add_default_user_img.png';
        $recode1['sun_moon_asc'] = $wechat_recode['sun_moon_asc'];
        return $recode1;
    }


//    public function testAesAdd()
//    {
////        鉴爱邀请：`/web/identify_love/add?rid=参数`
////
////    参数：AES加密(rid=参数，注意是用户自己的rid)
////
////    加密方式：类似Header里的加密方式；
////
////    注意事项：参数里一定不能存在空格；
////
////    例如：HOST+/web/identify_love/add?token=kQToLukkYCdtIYoWhH+TMw==
//
//        $data = [
//            'rid' => '553540',
//        ];
//
//        print_r('———————————————————————————加密之前的内容———————————————————————————' . PHP_EOL);
//        print_r($data);
//
//        print_r('———————————————————————————加密之后的内容———————————————————————————' . PHP_EOL);
//        $token = IAuth::setSign($data);
//        print_r($token . PHP_EOL);
//        $token='Km1TdNLDPK33qSUqF1y7nA==';
//        print_r('———————————————————————————开始解密———————————————————————————' . PHP_EOL);
//        //注意token中不能存在空格，因为php的urldecode方法会把“+”替换成空格
//        $token = urldecode($token);
//        //把空格替换成“+”
//        $token = str_replace(' ', '+', $token);
//
//        // access-token AES解密
//        $result = (new Aes())->decryptWithOpenssl($token);
//        if (!empty($result))
//        {
//            //参数转换为数组
//            $array = array();
//            $paramArrs = explode('&', $result);
//            foreach ($paramArrs as $paramArr)
//            {
//                $array[strstr($paramArr, '=', true)] = substr(strstr($paramArr, '='), 1);
//            }
//            //参数赋值
////            $rid = $array['rid'];
//        }
//        print_r('———————————————————————————解密后的内容———————————————————————————' . PHP_EOL);
//        print_r($result);
//    }
////
//    public function testAesDetail()
//    {
////        鉴爱详情分享url=》HOST+ /web/identify_love/detail?token=参数
////
////        参数：AES加密(uid=参数&rid1=参数&rid2=参数&wid1=参数&wid2=参数【rid1和wid1二选一、rid2和wid2二选一】)
////
////    加密方式：类似Header里的加密方式；
////
////    注意事项：参数里一定不能存在空格；
////
////    例如：HOST+ /web/identify_love/detail?token=gBdLZ4xY2Za00bQUeNa3WQgCLSxSOMh1NZ3sQFF/AcN2udEDTwWiztesFOiI3iqY
//
//        $data = [
//            'uid' => '10254556',
//            'rid1' => '553540',
//            'rid2' => '',
//            'wid1' => '',
//            'wid2' => '4',
//        ];
//
//        print_r('———————————————————————————加密之前的内容———————————————————————————' . PHP_EOL);
//        print_r($data);
//
//        print_r('———————————————————————————加密之后的内容———————————————————————————' . PHP_EOL);
//        $token = IAuth::setSign($data);
//        print_r($token . PHP_EOL);
//        print_r('———————————————————————————开始解密———————————————————————————' . PHP_EOL);
//
//        $token='+IUDPdXOlBrohyDFC0jp6PVg78h5/I6raH9vrI8Q0Ww=';
//
//        //注意token中不能存在空格，因为php的urldecode方法会把“+”替换成空格
//        $token = urldecode($token);
//        //把空格替换成“+”
//        $token = str_replace(' ', '+', $token);
//
//        // access-token AES解密
//        $result = (new Aes())->decryptWithOpenssl($token);
//        if (!empty($result))
//        {
//            //参数转换为数组
//            $array = array();
//            $paramArrs = explode('&', $result);
//            foreach ($paramArrs as $paramArr)
//            {
//                $array[strstr($paramArr, '=', true)] = substr(strstr($paramArr, '='), 1);
//            }
//            //参数赋值
////            $rid = $array['rid'];
//        }
//        print_r('———————————————————————————解密后的内容———————————————————————————' . PHP_EOL);
//        print_r($result);
//    }
}
